package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @BelongsProject:hm-dianping
 * @BelongsPackage:com.hmdp.utils
 * @Author:zouchangjin
 * @CreateTime:2025-07-10 00:14
 * @Version:1.0
 */
public class ILockImpl implements ILock {

    private static final String KEY_PREFIX = "lock:";

    private static final String UUID_LOCK = UUID.randomUUID().toString(true) + "-";

    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;

    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    private String name;

    private StringRedisTemplate stringRedisTemplate;

    public ILockImpl(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean tryLock(Long timeoutSec) {
        //获取线程标识
        String threadId = UUID_LOCK + Thread.currentThread().getId();
        //获取锁
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, threadId, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    /**
     * 使用lua编程语言，实现redis的原子性
     */
    @Override
    public void unlock() {
        //获取线程标识
        String threadId = UUID_LOCK + Thread.currentThread().getId();
        //调用lua脚本
        stringRedisTemplate.execute(UNLOCK_SCRIPT, Collections.singletonList(KEY_PREFIX + name),threadId);
    }

    /*@Override
    public void unlock() {
        //获取线程标识
        String threadId = UUID_LOCK + Thread.currentThread().getId();
        //获取锁中的id标识
        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
        //判断标识是否一致
        if(threadId.equals(id)){
            //释放锁
            stringRedisTemplate.delete(KEY_PREFIX + name);
        }

    }*/
}
